import { defineComponent, computed, ref, reactive } from "vue";
import styles from "./add.module.less";
import LPopup from "@/components/public/lPopup/lPopup";
import LForm, { LFormItem } from "@/components/public/lForm/lForm";
import { QuestionCircleFilled } from "@ant-design/icons-vue";
import { $menuList } from "@/api/menu/menu";
import _ from "lodash";
import { message } from "ant-design-vue";
import { isArray } from "@/common/utils";
export default defineComponent({
  props: {
    service: {
      type: Object,
      required: true,
    }
  },
  emits: ['change'],
  setup(props, { emit, expose }) {
    const lPopupRef = ref(null as any);
    const form_ori = {
      role_name: null,
      role_key: null,
      role_sort: 0,
      status: true,
      // 菜单选中项
      menu_ids: [],
      // 菜单半选项
      menu_ids_half: [],
      remark: null,
    }
    const state = reactive({
      role_id: null,
      form: _.cloneDeep(form_ori),
      rules: {
        role_name: [{ required: true, message: "角色名称不能为空" }],
        role_key: [{ required: true, message: "权限字符不能为空" }],
      },
      // 菜单加载完成
      menu_loaded: false,
      menus: [],
      all: [],
    } as any)
    const isEdit = computed(() => {
      return state.role_id;
    })
    const getDetail = () => {
      props.service.detail({
        role_id: state.role_id,
      }).then((res: any) => {
        state.form.role_name = res.data?.role_name || null;
        state.form.role_key = res.data?.role_key || null;
        state.form.role_sort = res.data?.role_sort || 0;
        state.form.status = res.data?.status === '1' ? true : false;
        let menu_ids = res.data?.menu_ids || [];
        // 全选项
        state.form.menu_ids = menu_ids.filter((x:any) => state.all.findIndex((y:any) => y.parent_id === x) === -1) || [];
        // 半选项
        state.form.menu_ids_half = menu_ids.filter((x:any) => state.all.findIndex((y:any) => y.parent_id === x) > -1) || []; 
        state.form.remark = res.data?.remark || null;
      })
    }
    const open = (role_id?: number) => {
      if(!state.menu_loaded) {
        message.error('菜单未加载完成!');
        return;
      }
      state.role_id = role_id || null;
      if (state.role_id) {
        getDetail();
      }
      lPopupRef.value.open();
    }
    $menuList({}).then((res: any) => {
      state.menus = res?.data?.menu_list || [];
      state.all = res?.data?.all || [];
    }).finally(() => {
      state.menu_loaded = true;
    })
    const treeCheck = (checkedKeys:any,e:any) => {
      state.form.menu_ids_half = e.halfCheckedKeys || [];
    }
    const closed = () => {
      Object.entries(_.cloneDeep(form_ori)).forEach((items: any) => {
        state.form[items[0]] = items[1];
      })
      state.menu_ids = [];
    }
    const editConfirm = async () => {
      try {
        const res = await props.service.edit({
          role_id: state.role_id,
          role_name: state.form.role_name,
          role_key: state.form.role_key,
          role_sort: state.form.role_sort,
          status: state.form.status ? '1' : '0',
          remark: state.form.remark,
          menu_ids: state.form.menu_ids?.length > 0 ? state.form.menu_ids.concat(state.form.menu_ids_half).join(',') : '',
        });
        message.success('编辑成功!');
      } catch (err) { }
    }
    const addConfirm = async () => {
      try {
        const res = await props.service.add({
          role_name: state.form.role_name,
          role_key: state.form.role_key,
          role_sort: state.form.role_sort,
          status: state.form.status ? '1' : '0',
          remark: state.form.remark,
          menu_ids: state.form.menu_ids?.length > 0 ? state.form.menu_ids.concat(state.form.menu_ids_half).join(',') : '',
        });
        message.success('添加成功!');
      } catch (err) { }
    }
    const save = async (e: any) => {
      if (isEdit.value) {
        await editConfirm();
      } else {
        await addConfirm();
      }
      e?.done();
      lPopupRef.value.close();
      emit('change');
    }
    expose({
      open,
    })
    return () => (
      <LPopup title={isEdit.value ? '编辑角色' : '添加角色'} ref={lPopupRef} onClosed={() => closed()}>
        <div style={{ width: "700px", margin: "0 auto" }}>
          <LForm
            btns={["cancel", "confirm"]}
            v-model={state.form}
            rules={state.rules}
            onCancel={() => { lPopupRef.value.close() }}
            onConfirm={(e) => { save(e) }}
          >
            <LFormItem label="角色名称" prop="role_name">
              <a-input v-model={[state.form.role_name, 'value']} placeholder="请输入角色名称..." />
            </LFormItem>
            <LFormItem label={() => (
              <span>
                <a-tooltip placement="top" v-slots={{
                  title: () => (
                    <span>后端定义的权限字符</span>
                  )
                }}>
                  <QuestionCircleFilled style={{ marginRight: '5px' }} />
                </a-tooltip>
                权限字符
              </span>
            )} prop="role_key">
              <a-input v-model={[state.form.role_key, 'value']} placeholder="请输入角色字符..." />
            </LFormItem>
            <LFormItem label="角色顺序" prop="role_sort">
              <a-input-number style={{ width: '150px' }} min={0} v-model={[state.form.role_sort, 'value']} placeholder="请输入角色顺序..." />
            </LFormItem>
            <LFormItem label="状态" prop="status">
              <a-switch v-model={[state.form.status, 'checked']} />
            </LFormItem>
            <LFormItem label="菜单权限" prop="menu_ids">
              <div class={styles.treeArea}>
                <a-tree
                  v-model={[state.form.menu_ids, 'checkedKeys']}
                  checkable
                  selectable={false}
                  fieldNames={{ children: "childlist", title: 'menu_name', key: 'menu_id' }}
                  tree-data={state.menus}
                  onCheck={treeCheck}
                >
                </a-tree>
              </div>
            </LFormItem>
            <LFormItem label="备注" prop="remark">
              <a-textarea v-model={[state.form.remark, 'value']} placeholder="请填写备注..."></a-textarea>
            </LFormItem>
          </LForm>
        </div>
      </LPopup>
    )
  }
});
